package br.com.rapidrest.demo.web.engine;

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.ejb.EJB;

import br.com.rapidrest.annotation.Inject;
import br.com.rapidrest.demo.domain.PhoneBook;
import br.com.rapidrest.demo.service.PhoneBookService;
import br.com.rapidrest.util.MessagesBundle;

public class Home implements Serializable {

	private static final long serialVersionUID = -2556578578561210743L;

	@Inject
	private MessagesBundle messages;

	@EJB
	private PhoneBookService phoneBookService;

	public Object removePhoneBook(Long phoneBookId) {
		phoneBookService.removePhoneBook(phoneBookId);
		return Home.class;
	}

	public MessagesBundle getMessages() {
		return messages;
	}

	public List<PhoneBook> getPhoneBooks() {
		List<PhoneBook> phoneBooks = phoneBookService.findPhoneBooks();
		Collections.sort(phoneBooks, new Comparator<PhoneBook>() {

			@Override
			public int compare(PhoneBook o1, PhoneBook o2) {
				final Comparator<String> strComparator = String.CASE_INSENSITIVE_ORDER;
				String name1 = o1.getName();
				if (name1 == null) {
					return 1;
				}
				String name2 = o2.getName();
				if (name2 == null) {
					return -1;
				}
				return strComparator.compare(name1, name2);
			}

		});
		return phoneBooks;
	}

}